package com.hhf.job.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhf.job.config.BaseJobConfig;
import com.hhf.job.controller.basic.ResponseResult;
import com.hhf.job.entity.BaseJob;
import com.hhf.job.entity.BaseJobLog;
import com.hhf.job.service.BaseJobLogService;
import com.hhf.job.service.BaseJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理页接口
 */
@Slf4j
@Controller
@RequestMapping
public class AdminController {
    @Autowired
    private BaseJobService baseJobService;
    @Autowired
    private BaseJobConfig baseJobConfig;
    @Autowired
    private BaseJobLogService baseJobLogService;

    @GetMapping("/")
    public String getAllJob(HttpServletRequest request, BaseJob job) {
        List<BaseJob> allJob = baseJobService.getAllJob(job);
        request.setAttribute("allJob", allJob);
        return "/baseJob";
    }
    @GetMapping("/editJob")
    public String editJob(HttpServletRequest request, Integer jobId) {
        BaseJob job = baseJobService.getJobById(jobId);
        request.setAttribute("job",job);
        return "/editJob";
    }

    @GetMapping("/addJob")
    public String editJob(HttpServletRequest request) {
        request.setAttribute("job",new BaseJob());
        return "/editJob";
    }

    @PostMapping("/saveBaseJob")
    public String saveBaseJob(HttpServletRequest request, HttpServletResponse response, BaseJob baseJob) throws IOException {
        if(baseJob.getJobId() == null) {
            baseJob.setCreated(LocalDateTime.now());
            baseJob.setCreatedBy("1");
            baseJob.setExecStatus(0);
        }
        baseJobService.saveOrUpdate(baseJob);
        baseJobConfig.refreshAll();
        return "redirect:/";
    }
    @PostMapping("/delJob")
    @ResponseBody
    public ResponseResult delJob(HttpServletRequest request, Integer jobId) {
        baseJobService.removeById(jobId);
        baseJobConfig.refreshAll();
        return ResponseResult.success();
    }


    @GetMapping("/getJobLogDetail")
    public String getJobLogDetail(HttpServletRequest request, Long logId) {
        Assert.notNull(logId, "logId为空");
        BaseJobLog baseJobLog = baseJobLogService.getJobLogByLogId(logId);
        request.setAttribute("baseJobLog", baseJobLog);
        return "/baseJobLogDetail";
    }


    @GetMapping("/getJobLogPage")
    public String getJobLogPage(HttpServletRequest request, Integer jobId, Page<BaseJobLog> page) {
        Assert.notNull(jobId, "jobId为空");
        Page<BaseJobLog> jobLogPage = baseJobLogService.getJobLogPage(page,jobId);
        request.setAttribute("jobLogPage", jobLogPage);
        return "/baseJobLog";
    }

    /**
     * 手动执行任务
     * @param jobId
     * @return
     * @throws ClassNotFoundException
     */
    @PostMapping("/task/execTask")
    @ResponseBody
    public ResponseResult execTask(Integer jobId) {
        baseJobConfig.refreshAll();
        BaseJob job = baseJobService.getJobById(jobId);
        Assert.notNull(job, "任务不存在");
        if(job.getExecStatus() == 1) {
            throw new RuntimeException("任务正在执行，请稍后再试！");
        }
        boolean b = baseJobService.updateJobExecStatus(jobId, 0, 1);
        if(!b) {
            return ResponseResult.success();
        }
        BaseJobLog jobLog = new BaseJobLog();
        BeanUtils.copyProperties(job,jobLog);
        jobLog.setExecType(2);
        jobLog.setExecStatus(1);
        jobLog.setCreated(LocalDateTime.now());
        baseJobLogService.save(jobLog);
        try {
            Object resultObj = baseJobConfig.execTask(job);
            log.info("Job Result:{}", resultObj == null ? "" : resultObj.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            jobLog.setExecStatus(0);
            jobLog.setExecMsg(pringStackTraceToString(e));
        } finally {
            jobLog.setUpdated(LocalDateTime.now());
            baseJobLogService.saveOrUpdate(jobLog);
            baseJobService.updateJobExecStatus(jobId, 1, 0);
        }
        return ResponseResult.success();
    }

    private static String pringStackTraceToString(Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace( new PrintWriter(sw, true));
        return sw.getBuffer().toString();
    }

}
